package com.lisa.auto.service.c3.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.lisa.auto.entity.c3.model.BrandInfo;
import com.lisa.auto.entity.c3.model.Maker;
import com.lisa.auto.entity.c3.response.BaseResponse;
import com.lisa.auto.enums.C3UrlEnum;
import com.lisa.auto.mapper.c3.BrandInfoMapper;
import com.lisa.auto.service.c3.BrandInfoService;
import com.lisa.auto.service.c3.MakerService;
import com.lisa.auto.util.basic.BaseException;
import demo.C3ApiDemo;
import demo.request.BrandListRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 品牌管理信息 服务实现类
 * </p>
 *
 * @author hxh
 * @since 2019-12-20
 */
@Service
public class BrandInfoServiceImpl extends ServiceImpl<BrandInfoMapper, BrandInfo> implements BrandInfoService {

    @Value("${c3.url}")
    private String c3url;
    @Value("${c3.appKey}")
    private String appKey;
    @Value("${c3.secretKey}")
    private String secretKey;

    @Autowired
    private MakerService makerService;

    @Override
    public List<BrandInfo> queryBrandsToSave(String makerNo) {
        try {
            String url = c3url + C3UrlEnum.BRANDSURL.getUrl();
            BrandListRequest request = new BrandListRequest();
            request.setAppKey(appKey);
            request.setMakerNo(makerNo);
            String requestJson = JSONObject.toJSONString(request);
            String result = C3ApiDemo.get(url, requestJson, secretKey);
            if (StringUtils.isNotBlank(result)) {
                BaseResponse<BrandInfo> baseResponse = JSONObject.parseObject(result, BaseResponse.class);
                JSONObject jsonObject = JSONObject.parseObject(result);
                if (!baseResponse.isReturnSuccess()) {
                    throw new BaseException("获取品牌信息查询:" + baseResponse.getReturnErrMsg());
                }
                List<BrandInfo> list = JSON.parseArray(JSON.toJSONString(jsonObject.get("list")), BrandInfo.class);
                if (list != null) {
                    EntityWrapper<BrandInfo> wrapper = new EntityWrapper<>();
                    wrapper.eq("maker_no", makerNo);
                    baseMapper.delete(wrapper);
                    for (BrandInfo brandInfo : list) {
                        if (StringUtils.isNotBlank(brandInfo.getNo()))
                            baseMapper.insert(brandInfo);
                    }
                }
                return list;
            }
            return null;
        } catch (IOException e) {
            throw new BaseException(e.getMessage());
        } catch (Exception e) {
            throw new BaseException(e.getMessage());
        }
    }

    @Override
    public void addBrand(BrandInfo brandInfo) {
        if (StringUtils.isEmpty(brandInfo.getNo())) {
            throw new BaseException("品牌编码不能为空");
        }
        if (StringUtils.isEmpty(brandInfo.getName())) {
            throw new BaseException("品牌名称不能为空");
        }
        if (StringUtils.isEmpty(brandInfo.getMakerNo())) {
            throw new BaseException("制造商编码不能为空");
        }
        if (StringUtils.isEmpty(brandInfo.getMakerName())) {
            throw new BaseException("制造商名称不能为空");
        }
        //查询该车架号是否已存在，存在就更新，不存在就新增
        EntityWrapper<BrandInfo> ew = new EntityWrapper<>();
        ew.eq("no", brandInfo.getNo());
        ew.eq("maker_no", brandInfo.getMakerNo());
        List<BrandInfo> brandInfos = baseMapper.selectList(ew);
        if (brandInfos != null && !brandInfos.isEmpty()) {
            baseMapper.update(brandInfo, ew);
        } else {
            baseMapper.insert(brandInfo);
        }
    }

    @Override
    public void brandInfoUpdate(Maker maker) {
        if (maker == null || StringUtils.isEmpty(maker.getNo())) throw new BaseException("制造商编码为空");
        EntityWrapper<Maker> makerEW = new EntityWrapper<>();
        makerEW.eq("no", maker.getNo());
        List<Maker> makerList = makerService.selectList(makerEW);
        if (makerList == null || makerList.size() < 1) throw new BaseException("未找到对应制造商");
        List<BrandInfo> brandInfos = maker.getBrandInfos();
        if (brandInfos != null && !brandInfos.isEmpty()){
            for (BrandInfo brandInfo : brandInfos) {
                brandInfo.setMakerNo(maker.getNo());
                brandInfo.setMakerName(maker.getName());
                addBrand(brandInfo);
            }
        }
    }

    @Override
    public List<BrandInfo> getBrandsList(Map<String, Object> condition) {
        EntityWrapper<BrandInfo> ew = buildWrapper(condition);
        List<BrandInfo> list = baseMapper.selectList(ew);
        return list;
    }

    @Override
    public Page<BrandInfo> getBrandsListPage(Page<BrandInfo> page) {
        if (page == null) {
            throw new BaseException("参数不能为空");
        }
        EntityWrapper<BrandInfo> ew = buildWrapper(page.getCondition());
        List<BrandInfo> list = baseMapper.getBrandsListPage(ew, page);
        page.setRecords(list);
        return page;
    }

    private EntityWrapper<BrandInfo> buildWrapper(Map<String, Object> cd) {
        EntityWrapper<BrandInfo> ew = new EntityWrapper<>();
        if (cd != null) {
            if (Objects.nonNull(cd.get("no")) &&
                    StringUtils.isNotBlank(cd.get("no").toString())) {
                ew.like("no", cd.get("no").toString());
            }
            if (Objects.nonNull(cd.get("name")) &&
                    StringUtils.isNotBlank(cd.get("name").toString())) {
                ew.like("name", cd.get("name").toString());
            }
            if (Objects.nonNull(cd.get("makerNo")) &&
                    StringUtils.isNotBlank(cd.get("makerNo").toString())) {
                ew.like("maker_no", cd.get("makerNo").toString());
            }
            if (Objects.nonNull(cd.get("makerName")) &&
                    StringUtils.isNotBlank(cd.get("makerName").toString())) {
                ew.like("maker_name", cd.get("makerName").toString());
            }
            if (Objects.nonNull(cd.get("status")) &&
                    StringUtils.isNotBlank(cd.get("status").toString())) {
                ew.eq("status", cd.get("status").toString());
            }
            if (Objects.nonNull(cd.get("startDate")) && StringUtils.isNotEmpty((String) cd.get("startDate"))) {
                ew.ge("gmt_create", cd.get("startDate").toString());
            }
            if (Objects.nonNull(cd.get("endDate")) && StringUtils.isNotEmpty((String) cd.get("endDate"))) {
                ew.le("gmt_create", cd.get("endDate").toString());
            }
        }
        ew.orderBy("gmt_create", Boolean.FALSE);
        return ew;
    }

    @Override
    public void deleteByIds(String id) {
        if (StringUtils.isEmpty(id)) throw new BaseException("参数为空");
        String[] ids = id.split(",");
        EntityWrapper<BrandInfo> ew = new EntityWrapper<>();
        ew.in("id", ids);
        List<BrandInfo> brandInfos = baseMapper.selectList(ew);
        if (brandInfos == null || brandInfos.size() < 1) throw new BaseException("未查询到对应品牌信息");
        for (BrandInfo brandInfo : brandInfos) {
            if ("50".equals(brandInfo.getStatus())) throw new BaseException("存在已删除品牌");
        }
        BrandInfo info = new BrandInfo();
        info.setStatus("50");
        info.setGmtModified(new Date());
        baseMapper.update(info, ew);
    }

    @Override
    public void forbiddenByIds(String id) {
        if (StringUtils.isEmpty(id)) throw new BaseException("参数为空");
        String[] ids = id.split(",");
        EntityWrapper<BrandInfo> ew = new EntityWrapper<>();
        ew.in("id", ids);
        List<BrandInfo> brandInfos = baseMapper.selectList(ew);
        if (brandInfos == null || brandInfos.size() < 1) throw new BaseException("未查询到对应品牌信息");
        for (BrandInfo brandInfo : brandInfos) {
            if ("50".equals(brandInfo.getStatus())) throw new BaseException("存在已删除品牌");
            if ("40".equals(brandInfo.getStatus())) throw new BaseException("存在已禁用品牌");
        }
        BrandInfo info = new BrandInfo();
        info.setStatus("40");
        info.setGmtModified(new Date());
        baseMapper.update(info, ew);
    }

    @Override
    public void enableByIds(String id) {
        if (StringUtils.isEmpty(id)) throw new BaseException("参数为空");
        String[] ids = id.split(",");
        EntityWrapper<BrandInfo> ew = new EntityWrapper<>();
        ew.in("id", ids);
        List<BrandInfo> brandInfos = baseMapper.selectList(ew);
        if (brandInfos == null || brandInfos.size() < 1) throw new BaseException("未查询到对应品牌信息");
        for (BrandInfo brandInfo : brandInfos) {
            if ("50".equals(brandInfo.getStatus())) throw new BaseException("存在已删除品牌");
            if ("10".equals(brandInfo.getStatus())) throw new BaseException("存在已启用品牌");
        }
        BrandInfo info = new BrandInfo();
        info.setStatus("10");
        info.setGmtModified(new Date());
        baseMapper.update(info, ew);
    }

}
